package com.laowang.project.system.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.NumUtil;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.project.system.domain.MyCarBook;
import com.laowang.project.system.domain.MyCyhMarkPrice;
import com.laowang.project.system.domain.WxUser;
import com.laowang.project.system.mapper.MyCarBookMapper;
import com.laowang.project.system.service.MyCarBookService;
import com.laowang.project.system.service.MyCyhMarkPriceService;
import com.laowang.project.system.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.MyCyhMark;
import com.laowang.project.system.service.MyCyhMarkService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * 副牌管理Controller
 *
 * @author laowang
 * @date 2023-05-05
 */
@Api(tags = "副牌管理接口")
@RestController
@RequestMapping("/mark")
public class MyCyhMarkController extends BaseController {

    List<Integer> list = Arrays.asList(1111,2222,3333,4444,6666);
    @Autowired
    private MyCyhMarkService myCyhMarkService;

    @Autowired
    private MyCyhMarkPriceService myCyhMarkPriceService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private MyCarBookService myCarBookService;

    @Autowired
    private MyCarBookMapper myCarBookMapper;

    @ApiOperation(value = "小程序端 已购副牌数量",notes = "")
    @GetMapping("/chooseTotal")
    public AjaxResult chooseTotal() {
        List<MyCyhMark> list = myCyhMarkService.selectMyCyhMarkList(null);

        return AjaxResult.success("操作成功",list.size());
    }

    @ApiOperation(value = "小程序端 我的副牌",notes = "")
    @GetMapping("/my")
    public AjaxResult my() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        MyCyhMark myCyhMark = new MyCyhMark();
        myCyhMark.setUserId(mid);
        List<MyCyhMark> myCyhMarks = myCyhMarkService.selectMyCyhMarkList(myCyhMark);
        return AjaxResult.success("操作成功",myCyhMarks);
    }

    @ApiOperation(value = "小程序端 会员领取副牌",notes = "")
    @GetMapping("/drawNumber")
    public AjaxResult drawNumber(Integer num,Integer type,String car,Integer typePower) {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        //MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(mid);

        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (Objects.isNull(wxUser.getVipLevel())){
            return AjaxResult.error("不是会员暂不送副牌");
        }else {
            List<MyCyhMark> list = myCyhMarkService.selectMyCyhMarkList(null);
            //List<String> collect = list.stream().map( MyCyhMark::getNumber).collect(Collectors.toList());
            //List<Integer> collect1 = collect.stream().map(Integer::parseInt).collect(Collectors.toList());
            List<String> collect1 =new ArrayList<>();
            for (MyCyhMark myCyhMark : list) {
                collect1.add(myCyhMark.getCarId()+myCyhMark.getNumber());
            }
            StringBuilder ran = new StringBuilder(num + "");
            while (ran.length()<4){
                ran.insert(0, "0");
            }
            String str = car + ran.toString();
            if (collect1.contains(str)){
                return AjaxResult.error("此号码被提前一步先选了");
            }

            //MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(mid);
            //String string ="";
            Integer type1 = NumUtil.getType(num);
            if (!type1.equals(type)){
                return AjaxResult.error("类型不匹配!",400);
            }

            MyCyhMark myCyhMark = new MyCyhMark();
            myCyhMark.setNumber(ran.toString());
            myCyhMark.setUserId(mid);
            myCyhMark.setNatime(new Date());
            myCyhMark.setCarId(car);
            myCyhMark.setTypePower(typePower);
            myCyhMarkService.insertMyCyhMark(myCyhMark);
        }

        return AjaxResult.success();
    }

    private int getRandom(List<String> collect1,String car) {
        int random = 0;
        Boolean flag = true;

        while (true) {
            if (!flag) break;
            random = (int) (Math.random() * 10000 + 101);
            StringBuilder ran = new StringBuilder(random + "");
            while (ran.length()<4){
                ran.insert(0, "0");
            }
            ran.insert(0,car);

            if (!collect1.contains(ran.toString())) {
                flag = false;
            }
        }
        return random;
    }

    @ApiOperation(value = "小程序端 随机副牌",notes = "")
    @GetMapping("/random")
    public AjaxResult random(Integer num,Integer type,String car,Integer typePower) {

        if (StringUtils.isEmpty(car)){
            throw new CustomException("车型不能为空",400);
        }
        List<MyCyhMark> list = myCyhMarkService.selectMyCyhMarkList(null);
        //List<String> collect = list.stream().map( MyCyhMark::getNumber).collect(Collectors.toList());
        //List<Integer> collect1 = collect.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<String> collect1 =new ArrayList<>();
        for (MyCyhMark myCyhMark : list) {
            collect1.add(myCyhMark.getCarId()+myCyhMark.getNumber());
        }
        Map<String,Object> map =new HashMap<>();
        if( Objects.isNull(num)){
            // 和车型挂钩了
            int random = getRandom(collect1,car);
            //价格
            Integer type1 = NumUtil.getType(random);

            while (!type1.equals(0)){
                random = getRandom(collect1,car);
                type1 = NumUtil.getType(random);
                //System.out.println("号码:"+random);
                //System.out.println("类型:"+type1);
            }


            MyCyhMarkPrice myCyhMarkPrice = myCyhMarkPriceService.selectMyCyhMarkPriceByType(type1);

            StringBuilder ran = new StringBuilder(random + "");
            while (ran.length()<4){
                ran.insert(0, "0");
            }
            map.put("price",myCyhMarkPrice.getAmount());
            map.put("random",ran.toString());
        }else {

            if (num<=100){
                return AjaxResult.error("该号已经被购买");
            }
            if (num >=10000){
                return AjaxResult.error("该号平台不支持");
            }
            StringBuilder ran = new StringBuilder(num + "");
            while (ran.length()<4){
                ran.insert(0, "0");
            }
            String str = car + ran.toString();
            if (collect1.contains(str)){
                return AjaxResult.error("该号码已经被占用");
            }

            Integer type1 = NumUtil.getType(num);
            if (!type1.equals(type)){
                throw new CustomException("类型不对应",400);
            }
            MyCyhMarkPrice myCyhMarkPrice = myCyhMarkPriceService.selectMyCyhMarkPriceByType(type1);

            map.put("random",ran.toString());
            map.put("price",myCyhMarkPrice.getAmount());
        }

        return AjaxResult.success("操作成功",map);
    }



    //@ApiOperation(value = "小程序端 靓号",notes = "")
    //@GetMapping("/brightNum")
    public AjaxResult brightNum() {

        List<Integer> list = Arrays.asList(1111,2222,3333,4444,6666);


        return AjaxResult.success("操作成功",list);
    }

    /**
     * 查询副牌管理列表
     */
    @ApiOperation(value = "查询副牌管理列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCyhMark myCyhMark) {
        startPage();
        List<MyCyhMark> list = myCyhMarkService.selectMyCyhMarkList(myCyhMark);
        return getDataTable(list);
    }

    /**
     * 导出副牌管理列表
     */
    @ApiOperation(value = "导出副牌管理列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:export')")
    @Log(title = "副牌管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCyhMark myCyhMark) {
        List<MyCyhMark> list = myCyhMarkService.selectMyCyhMarkList(myCyhMark);
        ExcelUtil<MyCyhMark> util = new ExcelUtil<MyCyhMark>(MyCyhMark.class);
        return util.exportExcel(list, "mark");
    }

    /**
     * 获取副牌管理详细信息
     */
    @ApiOperation(value = "获取副牌管理详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhMarkService.selectMyCyhMarkById(id));
    }

    /**
     * 新增副牌管理
     */
    @ApiOperation(value = "新增副牌管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:add')")
    @Log(title = "副牌管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhMark myCyhMark) {
        return toAjax(myCyhMarkService.insertMyCyhMark(myCyhMark));
    }

    /**
     * 修改副牌管理
     */
    @ApiOperation(value = "修改副牌管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:edit')")
    @Log(title = "副牌管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhMark myCyhMark) {
        return toAjax(myCyhMarkService.updateMyCyhMark(myCyhMark));
    }

    /**
     * 删除副牌管理
     */
    @ApiOperation(value = "删除副牌管理",notes = "")
    @PreAuthorize("@ss.hasPermi('my:mark:remove')")
    @Log(title = "副牌管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhMarkService.deleteMyCyhMarkByIds(ids));
    }
}
